package com.lst.selfaiagent.advisors;

import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.ai.chat.client.ChatClientRequest;
import org.springframework.ai.chat.client.ChatClientResponse;
import org.springframework.ai.chat.client.advisor.SimpleLoggerAdvisor;
import org.springframework.ai.chat.client.advisor.api.*;
import reactor.core.publisher.Flux;

/**
 * 自定义日志 Advisor
 * 打印 info 级别日志、只输出单次用户提示词和 AI 回复的文本
 */
public class MyLoggerAdvisor extends SimpleLoggerAdvisor {

    private static final Logger log = LoggerFactory.getLogger(MyLoggerAdvisor.class);

    public MyLoggerAdvisor() {
        super();
    }

    @Override
    public String getName() {
        return this.getClass().getSimpleName();
    }

    private void logRequest(ChatClientRequest request) {
        log.info("AI Request: {}", request.prompt().getContents());
    }

    private void logResponse(ChatClientResponse chatClientResponse) {
        if (chatClientResponse.chatResponse() != null && 
            chatClientResponse.chatResponse().getResult() != null && 
            chatClientResponse.chatResponse().getResult().getOutput() != null) {
            log.info("AI Response: {}", chatClientResponse.chatResponse().getResult().getOutput().getText());
        }
    }

    @Override
    public ChatClientResponse adviseCall(ChatClientRequest chatClientRequest, CallAdvisorChain callAdvisorChain) {
        logRequest(chatClientRequest);

        ChatClientResponse chatClientResponse = callAdvisorChain.nextCall(chatClientRequest);

        logResponse(chatClientResponse);

        return chatClientResponse;
    }

    @Override
    public Flux<ChatClientResponse> adviseStream(ChatClientRequest chatClientRequest,
                                                 StreamAdvisorChain streamAdvisorChain) {
        logRequest(chatClientRequest);

        Flux<ChatClientResponse> chatClientResponses = streamAdvisorChain.nextStream(chatClientRequest);

        return new org.springframework.ai.chat.client.ChatClientMessageAggregator()
                .aggregateChatClientResponse(chatClientResponses, this::logResponse);
    }
}